package quickstart.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import quickstart.model.Person;

@Transactional
public class PersonServiceImpl implements PersonService {
	@PersistenceContext
	private EntityManager em;
		
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

	private EntityManager getEntityManager(){
		return em;
	}
	
	@Override
	public Person find(int id) {
		return em.find(Person.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person> findAll() {
		Query query = em.createQuery("select p FROM Person p");
        return query.getResultList();
	}

	@Override
	public void remove(int id) {
		Person person = find(id);
        if (person != null) {
            em.remove(person);
        }		
	}

	@Override
	public void save(Person person) {
		if (person.getId() == null) {
			em.persist(person);	// new
		} else {
			em.merge(person);	// update
		}
	}

}
